import router from "./router";
import { useUserStore } from "./stores/user";
import { getProfile } from "./api/router";
import type { RouteRecordRaw } from "vue-router";
import { asyncRoutes } from "./router/asyncRoutes";
import { useMenuStore } from "./stores/mnue";

const WHITE_LIST = ["/login", "/404"];
// 处理一级路由
const firstLevelRoutes = (List: string[]) => {
  const array = List.map((item) => {
    return item.split(":")[0];
  });
  return Array.from(new Set(array));
};
// 处理二级路由
const secondLevelRoutes = (List: string[]) => {
  const array = List.map((item) => {
    return item.split(":")[0] + ":" + item.split(":")[1];
  });
  return Array.from(new Set(array));
};
// 过滤动态路由表
const filterRoutes = (
  firstLevelRoutesList: string[],
  secondLevelRoutesList: string[],
  asyncRoutes: RouteRecordRaw[]
) => {
  const store = useUserStore();
  // 超级管理员不过滤
  console.log('store',store.profile.permissions);
  if (store.profile.permissions[0].includes("*")) {
    // console.log('1111',1111);
    return [...asyncRoutes];
  }
  const firstRoutes = asyncRoutes.filter((item: RouteRecordRaw) => {
    return firstLevelRoutesList.includes(item.meta?.permission as string);
  });
  // console.log("filterRoutesList", firstRoutes);
  const lastRoutes = firstRoutes.map((route: RouteRecordRaw) => {
    return {
      ...route,
      children: route!.children!.filter((v) =>
        secondLevelRoutesList.includes(v.meta?.permission as string)
      ),
    };
  });
  return lastRoutes;
};
// 路由守卫
router.beforeEach(async (to, from, next) => {
  const store = useUserStore();
  if (store.token) {
    if (!store.profile.id) {
      const res = await getProfile();
      // console.log("res1111", res);
      store.setProfile(res.data);
      const firstLevelRoutesList = firstLevelRoutes(res.data.permissions);
      // console.log("firstLevelRoutesList", firstLevelRoutesList);
      const secondLevelRoutesList = secondLevelRoutes(res.data.permissions);
      // console.log("secondLevelRoutesList", secondLevelRoutesList);
      const last = filterRoutes(
        firstLevelRoutesList,
        secondLevelRoutesList,
        asyncRoutes
      );
      // console.log('last',last);
      last.forEach((item) => {
        router.addRoute(item);
      });
      const menuStore = useMenuStore();
      menuStore.setMenuList(last as RouteRecordRaw[]);
      next({ ...to });
    }
    next();
  } else {
    // 没有token
    if (WHITE_LIST.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }
});
